package com.xoa.service.party;

import com.xoa.dao.common.SysCodeMapper;
import com.xoa.dao.department.DepartmentMapper;
import com.xoa.dao.party.InformationDeliveryMapper;
import com.xoa.dao.users.UsersMapper;
import com.xoa.model.common.SysCode;
import com.xoa.model.department.Department;
import com.xoa.model.party.InformationDelivery;
import com.xoa.model.users.Users;
import com.xoa.util.DateFormat;
import com.xoa.util.ExcelUtil;
import com.xoa.util.GetAttachmentListUtil;
import com.xoa.util.ToJson;
import com.xoa.util.common.log.FileUtils;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.page.PageParams;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.beans.Transient;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class InformationDeliveryService {

    @Resource
    private InformationDeliveryMapper informationDeliveryMapper;
    @Resource
    private UsersMapper usersMapper;
    @Resource
    private DepartmentMapper departmentMapper;
    @Resource
    private SysCodeMapper sysCodeMapper;
    /**
     * 查询本社区的信息
     * @return
     */
    public ToJson selectInFo(HttpServletRequest request, Integer page, Integer pageSize, boolean useFlag){
            ToJson json=new ToJson();
            List<InformationDelivery> list=new ArrayList<>();
            Map<String,Object> map=new HashMap<String,Object>();
            int toal=0;
            try{
                Users user = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users());
                //查询所属社区
                Map<String,Object> gridName=informationDeliveryMapper.usergrId(user.getUserId());
                if(gridName!=null){
                    page=(page-1)*pageSize;
                    map.put("page",page);
                    map.put("pageSize",pageSize);
                    map.put("gridName",gridName.get("deptId")+"");
                // 查询所属社区的信息
                    list=informationDeliveryMapper.selectgrIdJl(map);
                 //分页
                    toal=informationDeliveryMapper.selectCount(gridName.get("deptId")+"");
                }
                if(list.size()>0){
                    json.setObj(list);
                    json.setObject(toal);
                    json.setFlag(0);
                    json.setMsg("ok");
                    return json;
                }
                json.setObj(list);
                json.setFlag(0);
                json.setObj(list);
                json.setObject(toal);
                json.setMsg("无数据");
            }catch (Exception e){
                e.printStackTrace();
            }
            return json;
    }


    /**
     * 新建信息报送前生成
     * @param request
     * @param
     * @return
     */
    public ToJson Insertinto(HttpServletRequest request){
             ToJson json=new ToJson();
             Map<String,Object> map=new HashMap<String,Object>();
             Users user = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users());
             Date currentTime = new Date();
             SimpleDateFormat formatterdate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
             SimpleDateFormat formatter = new SimpleDateFormat("yyyyMM");
             String bianhao=null;
             try {
               //查询本月文件
              String tin=informationDeliveryMapper.selectye();
              if(tin!=null){
                  String idun[]=tin.split("-");
                  if(idun[1]!=null){
                      Integer nian=Integer.valueOf(idun[1]);
                      if(idun[2]!=null){
                          Integer yue=Integer.valueOf(idun[2])+1;
                          bianhao=idun[0]+"-"+strCount(nian,"jly")+"-"+strCount(yue,"nian");
                      }
                  }
                 }else {
                  // 查询本年文件
                  String jly=informationDeliveryMapper.selectmath();
                  if(jly==null){
                      bianhao="SY"+formatter.format(currentTime)+"-"+"01"+"-0001";
                  }else {
                      String idun[]=jly.split("-");
                      if(idun[1]!=null){
                          Integer nian=Integer.valueOf(idun[1])+1;
                          if(idun[2]!=null){
                              bianhao=idun[0]+"-"+strCount(nian,"jly")+"-"+"-0001";;
                          }
                      }
                  }
              }
                 //查询所属社区
                 Map<String,Object> gridName=informationDeliveryMapper.usergrId(user.getUserId());
                 String  date=formatterdate.format(currentTime);
                 map.put("bianhao",bianhao);
                 map.put("gridName",gridName.get("deptName")+"");
                 map.put("deptId",gridName.get("deptId")+"");
                 map.put("userId",user.getUserId());
                 map.put("userName",user.getUserName());
                 map.put("date",date);
                 json.setObject(map);
                 json.setFlag(0);
                 json.setMsg("ok");
             }catch (Exception e){
                 e.printStackTrace();
             }
             return json;
    }

    /**
     * 添加位数
     * @param counrStr
     * @return
     */

    public  String  strCount(Integer counrStr,String tin){
        if(tin.equals("jly")){
            return  String.format("%02d", counrStr);
        }
        return  String.format("%04d", counrStr);
    }

    /**
     * 新建信息报送
     * @param request
     * @param informationDelivery
     * @return
     */
    @Transient
    public ToJson InsetInfro(HttpServletRequest request, InformationDelivery informationDelivery){
        ToJson json = new ToJson<>();
        Users user = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users());
        try {
            //查询所属社区
            Map<String, Object> gridName = informationDeliveryMapper.usergrId(user.getUserId());
            informationDelivery.setGridName(gridName.get("deptName") + "");
            informationDelivery.setSendCommunityCommunity(gridName.get("deptId") + "");
            informationDelivery.setUserName(user.getUserName());
            informationDelivery.setUserid(user.getUserId());
            if (user.getDeptId() != null) {
                informationDelivery.setSendCommunityCommunity(user.getDeptId().toString());
            }
            int count = informationDeliveryMapper.insert(informationDelivery);
            if (count > 0) {
                json.setFlag(0);
                json.setMsg("ok");
                return json;
            }
            json.setFlag(0);
            json.setMsg("添加失败");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return json;
    }
    /**
     * 查看数据/导出pdf
     * @param infoid
     * @return
     */
     public ToJson updateinser(HttpServletRequest request, Integer infoid){
               String sqlType = "xoa"
                 + (String) request.getSession().getAttribute("loginDateSouse");
              Users user = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users());
              ToJson json=new ToJson();
              String exintyp=request.getParameter("exintyp");
              try{
              if(exintyp!=null){
                  //导出pdf一条记录
                  if(exintyp.equals("1")){

                  }else {
                      //查看回显
                      InformationDelivery informationDelivery=informationDeliveryMapper.selectByPrimaryKey(infoid);
                      //解析附件
                      if(informationDelivery!=null){
                          if(informationDelivery.getEnclosureid()!=null && informationDelivery.getEnclosure()!=null){
                              informationDelivery.setAttachments1(GetAttachmentListUtil.returnAttachment(informationDelivery.getEnclosure(),informationDelivery.getEnclosureid(),sqlType, GetAttachmentListUtil.MODULE_INFO));
                          }
                          if(informationDelivery.getKongBai()!=null && informationDelivery.getKongBaia()!=null){
                              informationDelivery.setAttachments2(GetAttachmentListUtil.returnAttachment
                                      (informationDelivery.getKongBaia(),informationDelivery.getKongBai(),
                                              sqlType, GetAttachmentListUtil.MODULE_INFO));
                          }
                          Map<String, Object> gridName = informationDeliveryMapper.usergrId(informationDelivery.getUserid());
                          informationDelivery.setGridName(gridName.get("deptName") + "");
                          String userName=usersMapper.getUsernameByUserId(informationDelivery.getUserid());
                          informationDelivery.setUserName(userName);
                          json.setObject(informationDelivery);
                          json.setFlag(0);
                          json.setMsg("ok");
                          return json;
                      }
                      json.setMsg("异常");
                      json.setFlag(0);
                  }
              }else {
                  //查看回显
                  InformationDelivery informationDelivery=informationDeliveryMapper.selectByPrimaryKey(infoid);
                  //解析附件
                  if(informationDelivery!=null){
                      if(informationDelivery.getEnclosureid()!=null && informationDelivery.getEnclosure()!=null){
                          informationDelivery.setAttachments1(GetAttachmentListUtil.returnAttachment(informationDelivery.getEnclosure(),informationDelivery.getEnclosureid(),sqlType, GetAttachmentListUtil.MODULE_INFO));
                      }
                      if(informationDelivery.getKongBai()!=null && informationDelivery.getKongBaia()!=null){
                          informationDelivery.setAttachments2(GetAttachmentListUtil.returnAttachment(informationDelivery.getKongBaia(),informationDelivery.getKongBai(),sqlType, GetAttachmentListUtil.MODULE_INFO));
                      }
                      Map<String, Object> gridName = informationDeliveryMapper.usergrId(informationDelivery.getUserid());
                      informationDelivery.setGridName(gridName.get("deptName") + "");
                      String userName=usersMapper.getUsernameByUserId(informationDelivery.getUserid());
                      informationDelivery.setUserName(userName);
                      json.setObject(informationDelivery);
                      json.setFlag(0);
                      json.setMsg("ok");
                      return json;
                  }
                  json.setMsg("异常");
                  json.setFlag(0);
              }
              }catch (Exception e){
                  e.printStackTrace();
              }
              return json;
     }

    /**
     * 编辑
     * @param request
     * @param informationDelivery
     * @return
     */
    @Transient
     public ToJson updateinfo(HttpServletRequest request, InformationDelivery informationDelivery){
               ToJson json=new ToJson();
               try{
               int count=informationDeliveryMapper.updateByPrimaryKey(informationDelivery);
               if(count>0){
                   json.setFlag(0);
                   json.setMsg("ok");
                   return json;
               }
                   json.setMsg("异常");
                   json.setFlag(0);
               }catch (Exception e){
                   e.printStackTrace();
               }
               return json;
     }

    /**
     * 删除
     * @param request
     * @param infoid
     * @return
     */
     public ToJson deleteinfo(HttpServletRequest request, Integer infoid){
         ToJson json=new ToJson();
         try {
             int count=informationDeliveryMapper.deleteByPrimaryKey(infoid);
             if(count>0){
                 json.setFlag(0);
                 json.setMsg("ok");
                 return json;
             }
             json.setMsg("异常");
             json.setFlag(0);
         }catch (Exception e){
             e.printStackTrace();
         }
         return json;
     }

    /**
     * 根据条件查询/导出
     * @param request
     * @param informationDelivery
     * @return
     */
     public ToJson selectInfoto(HttpServletRequest request, HttpServletResponse response, InformationDelivery informationDelivery, Integer page, Integer pageSize, boolean useFlag){
         ToJson json=new ToJson();
         String exintyp=request.getParameter("exintyp");
         PageParams params = new PageParams();
         try{
             Map<String,Object> map=new HashMap();
            map.put("page",page);
            map.put("pageSize",pageSize);
             params.setPageSize(pageSize);
             params.setPage(page);
             params.setUseFlag(useFlag);
             map.put("params",params);
             if (informationDelivery.getEndTime() != null && informationDelivery.getEndTime() != "") {
                 SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
                 Date date=sdf.parse(informationDelivery.getEndTime());
                 Calendar calendar  =  new GregorianCalendar();
                 calendar.setTime(date);
                 calendar.add(calendar.DATE,1);//把日期往后增加一天.整数往后推,负数往前移动
                 date=calendar.getTime();
                 String d = DateFormat.getDatestr(date);
                 informationDelivery.setEndTime(d);
             }
             if(informationDelivery.getSendCommunityCommunity()!=null && (!informationDelivery.getSendCommunityCommunity().equals(""))){//做转换特殊处理
                 SysCode sysCode=sysCodeMapper.getSingleCode("TYPE_OF_ACCOUNT",informationDelivery.getSendCommunityCommunity());
                 if(sysCode.getCodeName()!=null){
                     List<Department> list =departmentMapper.checkDep(sysCode.getCodeName());
                     if(list!=null){
                         informationDelivery.setSendCommunityCommunity(list.get(0).getDeptId()+"");
                     }
                 }
             }
             map.put("informationDelivery",informationDelivery);
             List<InformationDelivery> list=informationDeliveryMapper.selectInfoto(map);
             int count=informationDeliveryMapper.selectInfotocount(map);
             if(exintyp==null){
                 exintyp="0";
             }
             if(exintyp.equals("1")){
                 try {
                     if (list!=null &&list.size()>0){
                         for (InformationDelivery delivery:list){
                             String m="";
                             if (delivery.getInformationClassification()!=null){
                                 String[] a = delivery.getInformationClassification().split(",");
                                 for (int i=0;i<a.length;i++){
                                     if ("1".equals(a[i])){
                                         m=m+"综合治理," ;
                                     }else if ("2".equals(a[i])){
                                         m=m+"维稳安保," ;
                                     }else if ("3".equals(a[i])){
                                         m=m+"出租房屋与流动人口," ;
                                     }else if ("4".equals(a[i])){
                                         m=m+"反邪教," ;
                                     }else if ("5".equals(a[i])){
                                         m=m+"禁毒," ;
                                     }else if ("6".equals(a[i])){
                                         m=m+"交通安全," ;
                                     }else if ("7".equals(a[i])){
                                         m=m+"养犬," ;
                                     }else if ("8".equals(a[i])){
                                         m=m+"其他," ;
                                     }else  {
                                         m=m+"" ;
                                     }
                                 }
                                 delivery.setType(m);
                             }
                         }

                     }
                     HSSFWorkbook workbook1 = ExcelUtil.makeExcelHead("信息报送", 9);
                     String[] secondTitles = {"报送编号", "会议（活动）主题", "报送社区","报送人","信息类型"};
                     HSSFWorkbook workbook2 = ExcelUtil.makeSecondHead(workbook1, secondTitles);
                     // String[] beanProperty = {user.getDep().getDeptName(),"userName","userPrivName", "roleAuxiliaryName","online","sex","online","telNoDept","telNoDept","departmentPhone","email"};
                     String[] beanProperty = {"informationDelivery", "conferenceTheme", "gridName","userName","type"};

                     HSSFWorkbook workbook = ExcelUtil.exportExcelData(workbook2, list, beanProperty);
                     ServletOutputStream out = response.getOutputStream();

                     String filename = "信息报送导出.xls";
                     filename = FileUtils.encodeDownloadFilename(filename,
                             request.getHeader("user-agent"));
                     response.setContentType("application/vnd.ms-excel");
                     response.setHeader("content-disposition",
                             "attachment;filename=" + filename);
                     workbook.write(out);
                     out.flush();
                     out.close();
                 } catch (IOException e) {
                     e.printStackTrace();
                 } catch (IllegalAccessException e) {
                     e.printStackTrace();
                 } catch (InvocationTargetException e) {
                     e.printStackTrace();
                 } catch (NoSuchMethodException e) {
                     e.printStackTrace();
                 }
                 json.setFlag(0);
                 json.setMsg("ok");
                 return json;
             }else {
                 if(list.size()>0){
                     json.setObj(list);
                     json.setTotleNum(params.getTotal());
                     json.setFlag(0);
                     json.setMsg("ok");
                     return json;
                 }
                 json.setObj(list);
                 json.setTotleNum(params.getTotal());
                 json.setMsg("异常");
                 json.setFlag(0);
             }
         }catch (Exception e){
             e.printStackTrace();
         }
         return json;
     }

    /**
     * 统计数量
     * @return
     */
     public ToJson selectInfo(Integer year){
            ToJson json=new ToJson();
            try{
            int count1=informationDeliveryMapper.selectInfo1(year);
            int count2=informationDeliveryMapper.selectInfo2(year);
            int count3=informationDeliveryMapper.selectInfo3(year);
            int count4=informationDeliveryMapper.selectInfo4(year);
            int count5=informationDeliveryMapper.selectInfo5(year);
            int count6=informationDeliveryMapper.selectInfo6(year);
            int count7=informationDeliveryMapper.selectInfo7(year);
            int count8=informationDeliveryMapper.selectInfo8(year);
            Map<String,Object> map=new HashMap<String,Object>();
            Integer [] count={count1,count2,count3,count4,count5,count6,count7,count8};
            map.put("count",count);
            json.setObject(map);
            json.setMsg("ok");
            json.setFlag(0);
            }catch (Exception e){
                e.printStackTrace();
            }
            return json;
     }
}
